import pygtk
import pynotify
import re
import sys

from debug import debug

class Notifier:
    '''Notifies the user in pseudo-real-time'''
    def __init__(self):
        debug('Notifier OK')
        self.allow_notif = False
        self.achievements = [
            ['Found the keyboard', 'Pressed one key on the keyboard.',
             False, self.key_presser]
            ,
            ['Keyboard smasher', 'Pressed more than 100 keys.',
             False, self.key_smasher]
            ,
            ['Keyboard destroyer', 'Pressed more than 1000 keys.',
             False, self.key_destroyer]
            ,
            ['Found me!',
             'Found my source code. Please improve me!',
             False, self.found_me]
            ,
            ['Daddy!', 'Found the PyKeyLogger repository.',
             False, self.daddy]
            ,
            ['Facebook is evil!', 'You visited Facebook. Shame on you!',
             False, self.facebook]
            ,
            ['Prove me correct', 'Using CoqIde? I dare you.',
             False, self.prove_me_correct]
            ,
            ['(Lisp (srsly?))', 'So many parentheses, what are you typing?',
             False, self.lisp]
            ,
            ['Watching my stats',
             'Found Procrastimeter Analytics',
             False, self.stats]
        ]
        return

    def on_stats_update(self, e, s):
        self.check_lisp(e)
        self.check_facebook(e, s)
        self.check_distraction_prog(e,s)
        self.check_wikimagnets(e)
        self.check_google_reader(e)
        self.check_fps(e)
        self.check_stack_overflow(e)
        if self.allow_notif:
            self.achievement_handler(e, s)
        return

    def popuptext(self, title, message):
        if self.allow_notif:
           if not pynotify.init('Basics'):
               sys.exit(1)
           n=pynotify.Notification(title, message)

           try:
               if not n.show():
                   print 'Failed to send notification'
           except Exception:
               print 'Too many notifications, wait...'
        return

    def check_lisp(self, e):
        try:
            if e['keycount'][')'] > 3:
                self.popuptext('LISP DETECTED',
                               'Please change to a proper language')
            return
        except KeyError:
            return

    def check_facebook(self, e, s):
        if (('Facebook' in e['title']) and
            (s['websites']['Facebook']['ratio']>0.05)):
            self.popuptext('Non productive behaviour',
                           'Facebook decreases productivity, leave now.')
        return

    def check_distraction_prog(self, e, s):
        if ((e['process'] in ['xchat', 'Skype', 'vlc'])  and
            (s['processes'][e['process']]['ratio'] > 0.1)):
            self.popuptext('Distraction detected',
                           'Stop contacting the outside world')
        return

    def check_wikimagnets(self, e):
        if 'Magnet - Wikipedia' in e['title']:
            self.popuptext('F MAGNETS', 'How do they work ?')
        return

    def check_google_reader(self, e):
        if 'Google Reader' in e['title']:
            res = re.match('Google Reader \((\d+)\).*', e['title'])
            if res:
                nb_unread = res.groups()[0]
                self.popuptext(nb_unread + ' new items!',
                               'You don\'t have the time to read that...')

    def check_fps(self, e):
        try:
            if (e['keycount']['z'] > 3 and e['keycount']['q'] > 3
                and e['keycount']['d'] > 3):
                self.popuptext('WASD?',
                               'Are you playing a FPS!? Back to work!')
            return
        except KeyError:
            return

    def check_stack_overflow(self, e):
        if 'Stack Overflow' in e['title']:
            self.popuptext('Don\'t worry',
                           'I won\'t overflow on you, buddy :)')


    def achievement_handler(self, e, s):
        for a in self.achievements:
            if not a[2]:
                if a[3](e, s):
                    self.popuptext('ACHIEVEMENT UNLOCKED:\n' + a[0], a[1])
                    s['achievements'].append((a[0], a[1]))
                    a[2] = True
        return

    def key_presser(self, e, s):
        return s['sum']['keycount'] > 0

    def key_smasher(self, e, s):
        return s['sum']['keycount'] > 100

    def key_destroyer(self, e, s):
        return s['sum']['keycount'] > 1000

    def found_me(self, e, s):
        return ('procrastimeter' in e['title'] and
            'Google Project Hosting' in e['title'])

    def daddy(self, e, s):
        return ('SourceForge.net: Simple Python Keylogger' in
                e['title'])

    def facebook(self, e, s):
        return 'Facebook' in e['title']

    def prove_me_correct(self, e, s):
        return 'CoqIde' in e['title']

    def lisp(self, e, s):
        try:
            if e['keycount'][')'] > 4:
                return True
        except KeyError:
            return False

    def stats(self, e, s):
        return 'Procrastimeter Analytics' in e['title']
